import jsRsasign from 'jsrsasign';
import jwt_Key from "@/config/jwt_priKey";
import { Base64 } from 'js-base64';
const getSignCode = function (msg: any) {
  // 创建RSAKey对象
  let rsa = new jsRsasign.RSAKey();
  //因为后端提供的是pck#8的秘钥对，所以这里使用 KEYUTIL.getKey来解析秘钥
  let signPrivateKey = jwt_Key;
  // 将密钥转码,其实就是将头部尾部默认字符串去掉
  signPrivateKey = jsRsasign.KEYUTIL.getKey(signPrivateKey) as any;
  // 创建Signature对象，设置签名编码算法
  // alg:对应的是规则 需要和后端统一
  let sig = new jsRsasign.KJUR.crypto.Signature({
    "alg": "SHA256withRSA",
    "prov": "cryptojs/jsrsa",
    "prvkeypem": signPrivateKey
  } as any);
  // 初始化
  sig.init(signPrivateKey)
  // 传入待加密字符串
  sig.updateString(msg);
  // 生成密文
  let sign = jsRsasign.hextob64(sig.sign());
  return sign
}
const jwtSign = (data: any) => {
  let header: any = {
    "alg": "RS256",
    "typ": "JWT"
  };
  header = JSON.stringify(header);
  header = Base64.encode(header);
  header = header.replace(/\+/g,'-');
  header = header.replace(/\//g, '_');
  header = header.replace(/\=/g, '');

  data = JSON.stringify(data);
  data = Base64.encode(data);
  data = data.replace(/\+/g, '-');
  data = data.replace(/\//g, '_');
  data = data.replace(/\=/g, '');

  let fullData = header + '.' + data;
  fullData = getSignCode(fullData);
  fullData = fullData.replace(/\+/g, '-');
  fullData = fullData.replace(/\//g, '_');
  fullData = fullData.replace(/\=/g, '');
  let res = header + '.' + data + '.' + fullData;
  return res;
}

export default jwtSign;